<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>Chrome插件管理</h1>
    </div>

    <!-- 插件列表容器 -->
    <div class="plugin-container">
      <!-- 空状态 -->
      <el-empty v-if="pluginData.length === 0" description="暂无插件数据" class="empty-state">
        <template #image>
          <img src="/src/assets/vue.svg" alt="Empty" class="empty-image" />
        </template>
      </el-empty>

      <!-- 插件卡片网格 -->
      <div class="plugin-grid" v-else>
        <el-card v-for="plugin in pluginData" :key="plugin.id" class="plugin-card" shadow="hover">
          <div class="plugin-header">
            <div class="plugin-info">
              <h2 class="plugin-name">{{ plugin.name }}</h2>
              <div class="plugin-badge">
                <el-badge :value="plugin.version" type="primary" class="version-badge" />
                <el-badge v-if="plugin.enabled" value="已启用" type="success" class="status-badge" />
                <el-badge v-else value="已禁用" type="info" class="status-badge" />
                <span class="install-date">{{ formatDate(plugin.installDate) }}</span>
              </div>
            </div>
            <el-switch v-model="plugin.enabled" active-color="#13ce66" inactive-color="#ff4949"
              @change="handleToggle(plugin)" />
          </div>

          <div class="plugin-body">
            <div>
              <p class="plugin-description">{{ plugin.description || '无描述信息' }}</p>
            </div>
            <div class="plugin-body-btn">
              <el-button type="danger" size="small" @click="handleUninstall(plugin.id)"
                :loading="uninstallingId === plugin.id">
                卸载
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 状态管理 - 仅保留必要变量
const pluginData = ref([])
const uninstallingId = ref(null)

// 加载插件列表 - 简化版
const loadPlugins = async () => {
  try {
    if (typeof chrome !== 'undefined' && chrome.management) {
      // 真实Chrome环境下获取插件列表
      const extensions = await new Promise((resolve, reject) => {
        chrome.management.getAll((extensions) => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError)
          } else {
            resolve(extensions)
          }
        })
      })

      const currentPlugin = await new Promise((resolve, reject) => {
        chrome.management.getSelf((result) => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError)
          } else {
            resolve(result)
          }
        });
      })

      // 格式化Chrome插件数据
      pluginData.value = extensions.map(ext => (
        {
          id: ext.id,
          name: ext.name,
          description: ext.description || '无描述信息',
          version: ext.version,
          enabled: ext.enabled,
          installDate: new Date(ext.installType === 'development' ? Date.now() : ext.installDate).toISOString().split('T')[0],
          icons: ext.icons
        }
      ))

      // 隐藏当前本身插件信息展示
      pluginData.value = pluginData.value.filter(p => p.id !== currentPlugin.id);
    }
  } catch (err) {
    console.error('加载插件失败:', err)
    pluginData.value = []
  }
}

// 切换插件状态 - 简化版
const handleToggle = async (plugin) => {
  try {
    if (typeof chrome !== 'undefined' && chrome.management) {
      await new Promise((resolve, reject) => {
        chrome.management.setEnabled(plugin.id, plugin.enabled, () => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError)
          } else {
            resolve()
          }
        })
      })
      ElMessage.success(`${plugin.name} ${plugin.enabled ? '已启用' : '已禁用'}`)
    }
  } catch (err) {
    console.error('切换插件状态失败:', err)
    plugin.enabled = !plugin.enabled
    ElMessage.error('操作失败')
  }
}

// 卸载插件 - 简化版
const handleUninstall = async (id) => {
  const plugin = pluginData.value.find(p => p.id === id)
  if (!plugin) return

  try {
    uninstallingId.value = id
    if (typeof chrome !== 'undefined' && chrome.management) {
      await new Promise((resolve, reject) => {
        chrome.management.uninstall(id, { showConfirmDialog: true }, () => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError)
          } else {
            resolve()
          }
        })
      })
      pluginData.value = pluginData.value.filter(p => p.id !== id)
      ElMessage.success(`${plugin.name} 已卸载`)
    }
  } catch (err) {
    console.error('卸载插件失败:', err)
    ElMessage.error('卸载失败')
  } finally {
    uninstallingId.value = null
  }
}

// 日期格式化工具函数
const formatDate = (dateString) => {
  if (!dateString) return '未知日期'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 初始化
onMounted(() => {
  loadPlugins()
})
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body,
#app {
  width: 100%;
  height: 100%;
}
</style>

<style scoped lang="scss">
.app-container {
  width: 500px;
  height: 600px;
  padding: 10px;

  .page-header {
    margin-bottom: 20px;
    text-align: center;

    h1 {
      margin: 0;
    }
  }


  .plugin-container {
    height: calc(100% - 52px);
    overflow-y: auto;

    .empty-state {
      margin: 50px 0;

      .empty-image {
        width: 120px;
        height: 120px;
      }
    }

    .plugin-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;


      .plugin-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        transition: transform 0.3s ease;

        &:hover {
          transform: translateY(-5px);
        }

        .plugin-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 15px;
          padding-bottom: 10px;
          border-bottom: 1px solid #f0f0f0;


          .plugin-info {
            flex: 1;

            .plugin-name {
              margin: 0 0 10px 0;
              font-size: 18px;
              color: #303133;
            }

            .plugin-badge {
              display: flex;
              gap: 8px;

              .install-date {
                color: #909399;
                font-size: 12px;
              }

              .version-badge {
                background-color: #e6f7ff;
                color: #1890ff;
              }

              .status-badge {
                background-color: #f6ffed;
              }
            }
          }
        }

        .plugin-body {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;

          &:first-child {
            flex: 1;
          }

          .plugin-description {
            color: #606266;
            margin: 0 0 15px 0;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>